﻿/*
 * listener.cpp
 *
 *  Created on: 2017年2月17日
 *      Author: work
 */

#include <dm/export.hpp>

#define DM_API_OS_COM DM_API_EXPORT

#include <dm/os/com/listener.hpp>
#include <dm/os/log/logger.hpp>

namespace dm{
namespace os{
namespace com{

static const char* logModule = "CListener.com.os.dm";

CListener::CListener():m_state(Unlistening),m_addr(),m_connect(0){
	log().debug(THISMODULE "创建对象");
}

CListener::~CListener(){
	log().debug(THISMODULE "销毁对象");
	if( m_connect!=0 )
		delete m_connect;
}

bool CListener::setAddress( const CAddress& addr ){
	if( m_state==Listening )
		return false;

	switch( addr.getType()){
	case CAddress::TcpServer:
		if( addr.asTcpServer() )
			return checkAndSetAddress(*addr.asTcpServer());
		break;
	case CAddress::UdpServer:
		if( addr.asUdpServer() )
			return checkAndSetAddress( *addr.asUdpServer() );
		break;
	default:
		break;
	}

	return false;
}

bool CListener::checkAndSetAddress( const CTcpServerAddr& /*addr*/ ){
	return false;
}

bool CListener::checkAndSetAddress( const CUdpServerAddr& /*addr*/ ){
	return false;
}

bool CListener::startListen(){
	if( m_state==Unlistening ){
		if( openPort() ){
			m_state = Listening;
			return readyForAccept();
		}
	}
	return false;
}

bool CListener::stopListen(){
	if( m_state==Listening ){
		if( closePort()){
			m_state = Unlistening;
			return true;
		}
	}
	return false;
}

void CListener::handler_connection( const error_t& ec ){
	if( ec ){
		log().error(THISMODULE "接收连接错误%s",ec.message().c_str());
		stopListen();
	}else{
		log().debug(THISMODULE "接收到新的连接");
		setConnectOnConnect( m_connect );
		onNewConnection( m_connect );
	}
}

void CListener::setConnectOnConnect( device_t* /*connect*/ ){
	log().info(THISMODULE "默认函数不处理连接。子类应该在这里设置新连接参数");
}

void CListener::onNewConnection( device_t* connect ){
	log().warnning(THISMODULE "默认函数不处理连接，将被删除");
	if( connect!=0 ){
		delete connect;
	}
}

}
}
}


